package com.cww.study.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.cww.study.base.SysCode;
import com.cww.study.exception.CustomClException;
import com.cww.study.mapper.UserMapper;
import com.cww.study.mybatis.PageResultBean;
import com.cww.study.po.User;
import com.cww.study.service.ISysDbTimeService;
import com.cww.study.service.UserService;
import com.cww.study.vo.AddUserVO;
import com.cww.study.vo.LoginVO;
import com.cww.study.vo.QueryUserPageListVO;
import com.cww.study.vo.UpdateUserStateVO;
import com.github.pagehelper.page.PageMethod;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.List;


/**
 * @program: cww_project
 * @description:
 * @author: 陈亮
 * @create: 2022-03-12 13:41
 */
@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;
    @Value("${cww.superAdminLoginName}")
    private String superAdminLoginName;
    @Resource
    private ISysDbTimeService iSysDbTimeService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void saveUser(AddUserVO vo) {

        // 不允许登录名重复
        User user = BeanUtil.copyProperties(vo, User.class);
        if (StringUtils.isBlank(vo.getId())) {
            Example example = new Example(User.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("loginName", vo.getLoginName())
                    .andEqualTo("deleteFlag", SysCode.DELETE.NO_DELETE);
            int count = userMapper.selectCountByExample(example);
            if (count > 0) {
                throw new CustomClException("500", "该用户已存在,请修改登录名");
            }
            user.setDeleteFlag(SysCode.DELETE.NO_DELETE);
            user.setState(SysCode.STATE.USE);
            user.setCreateTime(iSysDbTimeService.getDbTime14());
            if (superAdminLoginName.equals(vo.getLoginName())) {
                user.setIsSuper(SysCode.ROlE.SUPER_ADMIN);//陈伟伟注册进来默认是超管
            } else {
                user.setIsSuper(SysCode.ROlE.USER);// 其他人默认一般角色
            }
            userMapper.insert(user);
        } else {
            userMapper.updateByPrimaryKeySelective(user);
            // 编辑之后的用户信息再次维护进redis
            stringRedisTemplate.opsForValue().set(SysCode.LOGIN_KEY + vo.getLoginName(), JSON.toJSONString(this.checkUser(user)));
        }
    }


    @Override
    public PageResultBean<User> queryUserPageList(QueryUserPageListVO vo) {
        PageMethod.startPage(vo);
        Example example = new Example(User.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("loginName", vo.getLoginName())
                .andEqualTo("deleteFlag", SysCode.DELETE.NO_DELETE);
        example.setOrderByClause("CREATE_TIME DESC");
        List<User> list = userMapper.selectByExample(example);
        list.forEach(this::checkUser);
        return new PageResultBean<>(list);
    }

    @Override
    public User getDetailById(String id) {
        return this.checkUser(userMapper.selectByPrimaryKey(id));
    }

    @Override
    public void updateUserState(UpdateUserStateVO vo) {

        User user = new User();
        user.setId(vo.getId());
        if ("d".equals(vo.getFlag())) {
            user.setDeleteFlag(SysCode.DELETE.DELETE);
        } else if ("u".equals(vo.getFlag())) {
            user.setState(SysCode.STATE.USE);
        } else if ("nu".equals(vo.getFlag())) {
            user.setState(SysCode.STATE.NO_USE);
        }
        userMapper.updateByPrimaryKeySelective(user);
    }

    @Override
    public void login(LoginVO vo) {
        Example example = new Example(User.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("loginName", vo.getLoginName())
                .andEqualTo("pwd", vo.getPwd())
                .andEqualTo("deleteFlag", SysCode.DELETE.NO_DELETE);
        User user = userMapper.selectOneByExample(example);
        if (user == null) {
            throw new CustomClException("10888", "请先注册用户");
        }
        // 登录成功将用户信息set进redis
        stringRedisTemplate.opsForValue().set(SysCode.LOGIN_KEY + vo.getLoginName(), JSON.toJSONString(this.checkUser(user)));
    }

    @Override
    public User getLoginUserInfoByRedis(String loginName) {
        return JSON.parseObject(stringRedisTemplate.opsForValue().get(SysCode.LOGIN_KEY + loginName), User.class);
    }


    private User checkUser(User user) {
        user.setSex("B".equals(user.getSex()) ? SysCode.BOY : SysCode.GIRL);
        user.setState(SysCode.STATE.USE.equals(user.getState()) ? SysCode.STATE.USE_NAME : SysCode.STATE.NO_USE_NAME);
        user.setIsSuper(SysCode.ROlE.USER.equals(user.getIsSuper()) ? SysCode.ROlE.USER_STR : SysCode.ROlE.SUPER_ADMIN_STR);
        return user;
    }
}
